import urllib

from django import template
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from django.utils.hashcompat import md5_constructor
from django.core.exceptions import ObjectDoesNotExist
import os

from avatar import AVATAR_DEFAULT_URL, AVATAR_STORAGE_DIR

try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO

try:
    from PIL import Image
except ImportError:
    import Image


register = template.Library()

def avatar_url(user, size):
    if not isinstance(user, User):
        try:
            user = User.objects.get(username=user)
        except User.DoesNotExist:
            return AVATAR_DEFAULT_URL
    try:
        avatar = user.avatar
    except ObjectDoesNotExist:
        return AVATAR_DEFAULT_URL
    if not avatar.thumbnail_exists():
       avatar.create_thumbnail(size)
    return avatar.avatar_url()
register.simple_tag(avatar_url)

def avatar(user, size=80, dom_id=None):
    if not isinstance(user, User):
        try:
            user = User.objects.get(username=user)
            alt = unicode(user)
            url = avatar_url(user, size)
        except User.DoesNotExist:
            url = AVATAR_DEFAULT_URL
            alt = _("Default Avatar")
    else:
        alt = unicode(user)
        url = avatar_url(user, size)
    if dom_id != None:
        return """<img id="%s" src="%s" alt="%s" width="%s" height="%s" />""" % (dom_id, url, alt,
            size, size)
    else:
        return """<img src="%s" alt="%s" width="%s" height="%s" />""" % (url, alt,
            size, size)
register.simple_tag(avatar)


def avatar_orig(user, size, dom_id=None):
    if not isinstance(user, User):
        try:
            user = User.objects.get(username=user)
        except User.DoesNotExist:
            url = AVATAR_DEFAULT_URL
            alt = _("Default Avatar")
            width = size
            height = size
            
    try:
        avatar = user.avatar
    except ObjectDoesNotExist:
        url = AVATAR_DEFAULT_URL
        alt = _("Default Avatar")
        width = size
        height = size
        avatar = None

    if avatar is not None:
        url = avatar.avatar_orig_url() 
        alt = _("Original Avatar")
   
        try:
            orig = avatar.avatar.storage.open(avatar.avatar.name, 'rb').read()
            image = Image.open(StringIO(orig))
        except IOError:
            return "not found"
        (w, h) = image.size

        if w > h:
            width = size
            height = ""
        else:
            width = ""
            heigth = size
 
    if dom_id != None:
        return """<img id="%s" src="%s" alt="%s" width="%s" height="%s" />""" % (dom_id, url, alt, width, height)
    else:
        return """<img src="%s" alt="%s" width="%s" height="%s" />""" % (url, alt, width, height)
register.simple_tag(avatar_orig)


